from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
from db import *
import connection


class QSqlAlchemyTableModel(QAbstractTableModel):
	def __init__(self, session, mapped_object=Asset):
		super(QSqlAlchemyTableModel, self).__init__()
		self.session = session
		self.dirty = False
		# now we have to check for the data of the mapped class :
		stored_object = session.query(mapped_object).all()
		for obj in stored_object:
			print (obj)
			

	def deleteRowFromTable(row):
		pass
		
	def sortByName(self):
		self.reset()


	def sortByCountryOwner(self):
		self.reset()


	def flags(self, index):
		if not index.isValid():
			return Qt.ItemIsEnabled
		return Qt.ItemFlags(
				QAbstractTableModel.flags(self, index)|
				Qt.ItemIsEditable)


	def data(self, index, role=Qt.DisplayRole):
		pass


	def headerData(self, section, orientation, role=Qt.DisplayRole):
		pass


	def rowCount(self, index=QModelIndex()):
		return 0


	def columnCount(self, index=QModelIndex()):
		return 5


	def setData(self, index, value, role=Qt.EditRole):
		print ("set data called")
		self.dirty = True
		self.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"),
				  index, index)
		return True


	def insertRows(self, position, rows=1, index=QModelIndex()):
		self.beginInsertRows(QModelIndex(), position, position + rows - 1)
		print ("insert row")
		self.endInsertRows()
		self.dirty = True
		return True


	def removeRows(self, position, rows=1, index=QModelIndex()):
		self.beginRemoveRows(QModelIndex(), position, position + rows - 1)
		print ("remove row")
		self.endRemoveRows()
		self.dirty = True
		return True


	def load(self):
		print ("load called")

	def save(self):
		print ("save called")
		


def initializeModel(model):
    model.setTable("person")

    model.setEditStrategy(QSqlTableModel.OnManualSubmit)
    model.select()

    model.setHeaderData(0, QtCore.Qt.Horizontal, "ID")
    model.setHeaderData(1, QtCore.Qt.Horizontal, "First name")
    model.setHeaderData(2, QtCore.Qt.Horizontal, "Last name")


def createView(title, model):
    view = QTableView()
    view.setModel(model)
    view.setWindowTitle(title)
    return view


if __name__ == '__main__':

    import sys

    app = QApplication(sys.argv)
    if not connection.createConnection():
        sys.exit(1)

    model = QSqlAlchemyTableModel()

    initializeModel(model)

    view1 = createView("Table Model (View 1)", model)
    view2 = createView("Table Model (View 2)", model)

    view1.show()
    view2.move(view1.x() + view1.width() + 20, view1.y())
    view2.show()

    sys.exit(app.exec_())
